import {defineStore} from 'pinia'

const userInfo_ = {
    userId: 0,
    userNickName: "",
    userUsername: "",
    email: "",
    headImg: "",
    signature: "",
    registerTime: '',
    lastLoginTime: '',
}

// 从sessionStorage 读取 用户登录信息和token
const user = JSON.parse(window.sessionStorage.getItem("userInfo")) ? JSON.parse(window.sessionStorage.getItem("userInfo")) : userInfo_
const token = JSON.parse(window.sessionStorage.getItem("token")) ? JSON.parse(window.sessionStorage.getItem("token")) : ""

// 创建一个新的 store 实例
const userStore = defineStore('userStore', {
    state: () => {
        return {
            userInfo: user,
            token: token,
        }
    },
    getters: {
        getHeaderImg() {
            if (this.userInfo) {
                return this.userInfo.headImg
            } else {
                return ""
            }
        },
        getUserId() {
            if (this.userInfo) {
                return this.userInfo.userId
            } else {
                return ""
            }
        },
        hasUserInfo() {
            return this.userInfo.userId !== 0;
        }
    },
    actions: {
        updateUserInfo(userInfo) {
            this.userInfo = userInfo
        },
        resetUserInfo() {
            this.userInfo = userInfo_
            this.token = ""
        },
        updateUserHeaderImg(headerImg) {
            this.userInfo.headerImg = headerImg
        },
        updateToken(token) {
            this.token = token
        }
    }
})

export default userStore